package com.canvasgames.texture;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;

public class TextureManager {
	
	protected HashMap<String, Integer> textureIds = new HashMap<String, Integer>();
	
	protected Context context;
	
	//Quản lý các bức ảnh nhỏ
	protected HashMap<Integer, Texture> textures = new HashMap<Integer, Texture>();
	
	public TextureManager(Context context) {
		this.context = context;
	}
	
	
	
	
	public void addTextures(Texture texture) {
		textures.put(texture.getId(), texture);
	}
	
	
	public Texture getTexture(int key) {
		return textures.get(key);
	}
	/*Load resource từ asset*/
	
	public int getTextureId(String key) {
		return textureIds.get(key);
	}
	
	public void loadResources(String id, int resId, GL10 gl) {
        InputStream is = context.getResources().openRawResource(resId);
        loadResources(id, is, gl);
	}
	
	
	public void loadResources(String id,  InputStream is, GL10 gl) {
		Bitmap bitmap;
        try {
            bitmap = BitmapFactory.decodeStream(is);
            Log.i("","---------------> texture size "  + bitmap.getWidth() + " " + bitmap.getHeight());
        } finally {
            try {
                is.close();
            } catch(IOException e) {
                // Ignore.
            }
        }
		loadResource(id, bitmap, gl);
	}
	
	public void loadResource(String id, Bitmap bitmap, GL10 gl) {
		int[] textures = new int[1];
        gl.glGenTextures(1, textures, 0);
        int mTextureID = textures[0];
        gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER,
                GL10.GL_NEAREST);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D,
                GL10.GL_TEXTURE_MAG_FILTER,
                GL10.GL_LINEAR);

        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S,
                GL10.GL_CLAMP_TO_EDGE);
        gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T,
                GL10.GL_CLAMP_TO_EDGE);

        gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE,
                GL10.GL_REPLACE);
        GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
        textureIds.put(id, mTextureID);
        bitmap.recycle();
	}
	
}
